<template>
  <el-dialog
    v-model="dialogVisible"
    title="短信详情"
    width="900px"
    :close-on-click-modal="false"
  >
    <div class="sms-detail">
      <!-- 基本信息 -->
      <el-card shadow="never" class="detail-card">
        <template #header>
          <div class="card-header">
            <span>基本信息</span>
            <div class="header-actions">
              <el-tag :type="getStatusTagType(smsData.status)">
                {{ getStatusText(smsData.status) }}
              </el-tag>
            </div>
          </div>
        </template>
        
        <el-row :gutter="20">
          <el-col :span="8">
            <div class="info-item">
              <span class="label">短信ID：</span>
              <span class="value">{{ smsData.id }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <span class="label">短信类型：</span>
              <el-tag :type="getTypeTagType(smsData.type)" size="small">
                {{ getTypeText(smsData.type) }}
              </el-tag>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <span class="label">优先级：</span>
              <el-tag :type="getPriorityTagType(smsData.priority)" size="small">
                {{ getPriorityText(smsData.priority) }}
              </el-tag>
            </div>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="8">
            <div class="info-item">
              <span class="label">发送方式：</span>
              <span class="value">{{ getSendModeText(smsData.sendMode) }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <span class="label">接收人数：</span>
              <span class="value">{{ smsData.recipientCount }} 人</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <span class="label">短信条数：</span>
              <span class="value">{{ smsData.messageCount }} 条</span>
            </div>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="8">
            <div class="info-item">
              <span class="label">发送人：</span>
              <span class="value">{{ smsData.sender }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <span class="label">创建时间：</span>
              <span class="value">{{ smsData.createTime }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <span class="label">发送时间：</span>
              <span class="value">{{ smsData.sendTime || '未发送' }}</span>
            </div>
          </el-col>
        </el-row>
        
        <div class="info-item full-width">
          <span class="label">短信内容：</span>
          <div class="content-box">{{ smsData.content }}</div>
        </div>
        
        <div v-if="smsData.remark" class="info-item full-width">
          <span class="label">备注：</span>
          <span class="value">{{ smsData.remark }}</span>
        </div>
      </el-card>

      <!-- 发送统计 -->
      <el-card shadow="never" class="detail-card">
        <template #header>
          <span>发送统计</span>
        </template>
        
        <div class="statistics">
          <div class="stat-item">
            <div class="stat-number success">{{ smsData.successCount || 0 }}</div>
            <div class="stat-label">发送成功</div>
          </div>
          <div class="stat-item">
            <div class="stat-number warning">{{ smsData.pendingCount || 0 }}</div>
            <div class="stat-label">发送中</div>
          </div>
          <div class="stat-item">
            <div class="stat-number danger">{{ smsData.failedCount || 0 }}</div>
            <div class="stat-label">发送失败</div>
          </div>
          <div class="stat-item">
            <div class="stat-number info">{{ smsData.replyCount || 0 }}</div>
            <div class="stat-label">已回复</div>
          </div>
        </div>
        
        <div class="progress-info">
          <div class="progress-label">
            发送进度：{{ smsData.successCount || 0 }}/{{ smsData.recipientCount }} 
            ({{ ((smsData.successCount || 0) / smsData.recipientCount * 100).toFixed(1) }}%)
          </div>
          <el-progress 
            :percentage="(smsData.successCount || 0) / smsData.recipientCount * 100"
            :color="getProgressColor((smsData.successCount || 0) / smsData.recipientCount * 100)"
          />
        </div>
      </el-card>

      <!-- 接收人列表 -->
      <el-card shadow="never" class="detail-card">
        <template #header>
          <div class="card-header">
            <span>接收人列表</span>
            <div class="header-actions">
              <el-button size="small" @click="refreshRecipients">
                <el-icon><Refresh /></el-icon>
                刷新
              </el-button>
              <el-button size="small" @click="exportRecipients">
                <el-icon><Download /></el-icon>
                导出
              </el-button>
            </div>
          </div>
        </template>
        
        <div class="table-toolbar">
          <el-input
            v-model="recipientSearch"
            placeholder="搜索手机号码或姓名"
            style="width: 300px"
            clearable
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
          
          <el-select v-model="recipientStatusFilter" placeholder="发送状态" style="width: 120px" clearable>
            <el-option label="全部" value="" />
            <el-option label="成功" value="success" />
            <el-option label="发送中" value="pending" />
            <el-option label="失败" value="failed" />
          </el-select>
        </div>
        
        <el-table
          :data="filteredRecipients"
          style="width: 100%"
          max-height="400"
        >
          <el-table-column prop="phoneNumber" label="手机号码" width="130" />
          <el-table-column prop="name" label="姓名" width="100" />
          <el-table-column prop="status" label="发送状态" width="100">
            <template #default="{ row }">
              <el-tag :type="getRecipientStatusTagType(row.status)" size="small">
                {{ getRecipientStatusText(row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="sendTime" label="发送时间" width="160" />
          <el-table-column prop="deliveryTime" label="送达时间" width="160" />
          <el-table-column prop="replyTime" label="回复时间" width="160" />
          <el-table-column prop="errorMessage" label="错误信息" min-width="150" show-overflow-tooltip />
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="{ row }">
              <el-button
                v-if="row.status === 'failed'"
                type="primary"
                size="small"
                link
                @click="retrySend(row)"
              >
                重发
              </el-button>
              <el-button
                v-if="row.replyContent"
                type="success"
                size="small"
                link
                @click="viewReply(row)"
              >
                查看回复
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <div class="table-pagination">
          <el-pagination
            v-model:current-page="recipientPage"
            v-model:page-size="recipientPageSize"
            :total="filteredRecipients.length"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            small
          />
        </div>
      </el-card>

      <!-- 发送日志 -->
      <el-card shadow="never" class="detail-card">
        <template #header>
          <div class="card-header">
            <span>发送日志</span>
            <div class="header-actions">
              <el-button size="small" @click="refreshLogs">
                <el-icon><Refresh /></el-icon>
                刷新
              </el-button>
              <el-button size="small" @click="exportLogs">
                <el-icon><Download /></el-icon>
                导出日志
              </el-button>
            </div>
          </div>
        </template>
        
        <div class="log-container">
          <div
            v-for="log in sendLogs"
            :key="log.id"
            class="log-item"
            :class="log.level"
          >
            <div class="log-time">{{ log.time }}</div>
            <div class="log-content">{{ log.message }}</div>
          </div>
        </div>
      </el-card>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">关闭</el-button>
        <el-button
          v-if="smsData.status === 'draft'"
          type="primary"
          @click="editSms"
        >
          编辑
        </el-button>
        <el-button
          v-if="smsData.status === 'failed'"
          type="success"
          @click="retrySendAll"
        >
          重新发送
        </el-button>
      </div>
    </template>

    <!-- 回复内容对话框 -->
    <el-dialog
      v-model="replyDialogVisible"
      title="回复内容"
      width="500px"
    >
      <div class="reply-content">
        <div class="reply-info">
          <div><strong>手机号码：</strong>{{ currentReply.phoneNumber }}</div>
          <div><strong>回复时间：</strong>{{ currentReply.replyTime }}</div>
        </div>
        <div class="reply-text">{{ currentReply.replyContent }}</div>
      </div>
    </el-dialog>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Refresh, Download, Search } from '@element-plus/icons-vue'

interface Props {
  visible: boolean
  smsData: any
}

interface Emits {
  (e: 'update:visible', value: boolean): void
  (e: 'edit', data: any): void
  (e: 'retry', data: any): void
}

const props = withDefaults(defineProps<Props>(), {
  visible: false,
  smsData: () => ({})
})

const emit = defineEmits<Emits>()

const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

// 接收人相关
const recipientSearch = ref('')
const recipientStatusFilter = ref('')
const recipientPage = ref(1)
const recipientPageSize = ref(20)

// 回复对话框
const replyDialogVisible = ref(false)
const currentReply = ref({})

// 发送日志
const sendLogs = ref([
  { id: 1, time: '2024-01-15 10:00:00', level: 'info', message: '开始发送短信任务' },
  { id: 2, time: '2024-01-15 10:00:05', level: 'info', message: '正在验证接收人手机号码...' },
  { id: 3, time: '2024-01-15 10:00:10', level: 'success', message: '手机号码验证完成，共150个有效号码' },
  { id: 4, time: '2024-01-15 10:00:15', level: 'info', message: '开始批量发送短信...' },
  { id: 5, time: '2024-01-15 10:01:30', level: 'success', message: '短信发送完成，成功145条，失败5条' },
  { id: 6, time: '2024-01-15 10:02:00', level: 'warning', message: '部分号码发送失败，原因：号码停机' }
])

// 接收人列表（模拟数据）
const recipients = ref([
  {
    id: 1,
    phoneNumber: '13800138001',
    name: '张三',
    status: 'success',
    sendTime: '2024-01-15 10:00:30',
    deliveryTime: '2024-01-15 10:00:35',
    replyTime: '2024-01-15 10:05:20',
    replyContent: '收到，谢谢！',
    errorMessage: ''
  },
  {
    id: 2,
    phoneNumber: '13800138002',
    name: '李四',
    status: 'failed',
    sendTime: '2024-01-15 10:00:32',
    deliveryTime: '',
    replyTime: '',
    replyContent: '',
    errorMessage: '号码停机'
  },
  {
    id: 3,
    phoneNumber: '13800138003',
    name: '王五',
    status: 'pending',
    sendTime: '2024-01-15 10:00:34',
    deliveryTime: '',
    replyTime: '',
    replyContent: '',
    errorMessage: ''
  }
])

// 过滤后的接收人列表
const filteredRecipients = computed(() => {
  let filtered = recipients.value

  if (recipientSearch.value) {
    filtered = filtered.filter(item =>
      item.phoneNumber.includes(recipientSearch.value) ||
      item.name.includes(recipientSearch.value)
    )
  }

  if (recipientStatusFilter.value) {
    filtered = filtered.filter(item => item.status === recipientStatusFilter.value)
  }

  return filtered
})

// 获取状态标签类型
const getStatusTagType = (status: string) => {
  const types: Record<string, string> = {
    draft: 'info',
    pending: 'warning',
    sending: 'warning',
    success: 'success',
    failed: 'danger',
    cancelled: 'info'
  }
  return types[status] || 'info'
}

// 获取状态文本
const getStatusText = (status: string) => {
  const texts: Record<string, string> = {
    draft: '草稿',
    pending: '待发送',
    sending: '发送中',
    success: '发送成功',
    failed: '发送失败',
    cancelled: '已取消'
  }
  return texts[status] || status
}

// 获取类型标签类型
const getTypeTagType = (type: string) => {
  const types: Record<string, string> = {
    notification: 'primary',
    verification: 'success',
    marketing: 'warning',
    alarm: 'danger'
  }
  return types[type] || 'primary'
}

// 获取类型文本
const getTypeText = (type: string) => {
  const texts: Record<string, string> = {
    notification: '通知短信',
    verification: '验证码',
    marketing: '营销短信',
    alarm: '告警短信'
  }
  return texts[type] || type
}

// 获取优先级标签类型
const getPriorityTagType = (priority: string) => {
  const types: Record<string, string> = {
    low: 'info',
    normal: 'primary',
    high: 'warning',
    urgent: 'danger'
  }
  return types[priority] || 'primary'
}

// 获取优先级文本
const getPriorityText = (priority: string) => {
  const texts: Record<string, string> = {
    low: '低',
    normal: '普通',
    high: '高',
    urgent: '紧急'
  }
  return texts[priority] || priority
}

// 获取发送方式文本
const getSendModeText = (sendMode: string) => {
  const texts: Record<string, string> = {
    single: '单个发送',
    batch: '批量发送',
    group: '群组发送'
  }
  return texts[sendMode] || sendMode
}

// 获取接收人状态标签类型
const getRecipientStatusTagType = (status: string) => {
  const types: Record<string, string> = {
    success: 'success',
    pending: 'warning',
    failed: 'danger'
  }
  return types[status] || 'info'
}

// 获取接收人状态文本
const getRecipientStatusText = (status: string) => {
  const texts: Record<string, string> = {
    success: '成功',
    pending: '发送中',
    failed: '失败'
  }
  return texts[status] || status
}

// 获取进度条颜色
const getProgressColor = (percentage: number) => {
  if (percentage < 50) return '#f56c6c'
  if (percentage < 80) return '#e6a23c'
  return '#67c23a'
}

// 刷新接收人列表
const refreshRecipients = () => {
  ElMessage.success('接收人列表已刷新')
}

// 导出接收人列表
const exportRecipients = () => {
  ElMessage.success('接收人列表导出成功')
}

// 重发单个
const retrySend = async (recipient: any) => {
  try {
    await ElMessageBox.confirm('确认重新发送给该接收人？', '确认操作')
    
    // 模拟重发
    recipient.status = 'pending'
    recipient.errorMessage = ''
    
    ElMessage.success('重发成功')
  } catch (error) {
    // 用户取消
  }
}

// 查看回复
const viewReply = (recipient: any) => {
  currentReply.value = recipient
  replyDialogVisible.value = true
}

// 刷新日志
const refreshLogs = () => {
  ElMessage.success('发送日志已刷新')
}

// 导出日志
const exportLogs = () => {
  ElMessage.success('发送日志导出成功')
}

// 编辑短信
const editSms = () => {
  emit('edit', props.smsData)
  dialogVisible.value = false
}

// 重新发送全部
const retrySendAll = async () => {
  try {
    await ElMessageBox.confirm('确认重新发送该短信？', '确认操作')
    emit('retry', props.smsData)
    dialogVisible.value = false
  } catch (error) {
    // 用户取消
  }
}
</script>

<style scoped>
.sms-detail {
  max-height: 70vh;
  overflow-y: auto;
}

.detail-card {
  margin-bottom: 20px;
}

.detail-card:last-child {
  margin-bottom: 0;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.info-item {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.info-item.full-width {
  flex-direction: column;
  align-items: flex-start;
}

.info-item .label {
  font-weight: 500;
  color: #666;
  min-width: 80px;
  margin-right: 10px;
}

.info-item .value {
  color: #333;
}

.content-box {
  margin-top: 8px;
  padding: 12px;
  background-color: #f8f9fa;
  border-radius: 4px;
  border: 1px solid #e9ecef;
  white-space: pre-wrap;
  word-break: break-all;
  width: 100%;
}

.statistics {
  display: flex;
  gap: 40px;
  margin-bottom: 20px;
}

.stat-item {
  text-align: center;
}

.stat-number {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 5px;
}

.stat-number.success {
  color: #67c23a;
}

.stat-number.warning {
  color: #e6a23c;
}

.stat-number.danger {
  color: #f56c6c;
}

.stat-number.info {
  color: #409eff;
}

.stat-label {
  font-size: 12px;
  color: #666;
}

.progress-info {
  margin-top: 20px;
}

.progress-label {
  margin-bottom: 10px;
  font-size: 14px;
  color: #666;
}

.table-toolbar {
  display: flex;
  gap: 15px;
  margin-bottom: 15px;
}

.table-pagination {
  margin-top: 15px;
  text-align: right;
}

.log-container {
  max-height: 300px;
  overflow-y: auto;
  border: 1px solid #e9ecef;
  border-radius: 4px;
}

.log-item {
  display: flex;
  padding: 8px 12px;
  border-bottom: 1px solid #f0f0f0;
}

.log-item:last-child {
  border-bottom: none;
}

.log-item.info {
  background-color: #f8f9fa;
}

.log-item.success {
  background-color: #f0f9ff;
}

.log-item.warning {
  background-color: #fffbf0;
}

.log-item.error {
  background-color: #fef0f0;
}

.log-time {
  min-width: 150px;
  font-size: 12px;
  color: #666;
  margin-right: 15px;
}

.log-content {
  flex: 1;
  font-size: 13px;
  color: #333;
}

.dialog-footer {
  text-align: right;
}

.reply-content {
  padding: 10px 0;
}

.reply-info {
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #e9ecef;
}

.reply-info div {
  margin-bottom: 5px;
  font-size: 14px;
  color: #666;
}

.reply-text {
  padding: 12px;
  background-color: #f8f9fa;
  border-radius: 4px;
  border-left: 4px solid #409eff;
  font-size: 14px;
  line-height: 1.6;
}

:deep(.el-card__header) {
  padding: 15px 20px;
  background-color: #fafafa;
  border-bottom: 1px solid #e9ecef;
}

:deep(.el-card__body) {
  padding: 20px;
}

:deep(.el-table) {
  font-size: 13px;
}

:deep(.el-progress-bar__outer) {
  height: 8px;
}
</style>